package com.sc.nft.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.sc.nft.admin.request.*;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.MarketTypeEnum;
import com.sc.nft.enums.PledgeTaskRewardTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.PledgeTaskInfoService;
import com.sc.nft.service.StaticDataService;
import com.sc.nft.service.UserPledgeCollectionRecordsService;
import com.sc.nft.service.UserVigorousCollectionRecordsService;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/pledge/task")
@Api(tags = "后台质押任务管理")
public class AdminPledgeTaskController {

    private final PledgeTaskInfoService pledgeTaskInfoService;
    private final DigitalCollectionDao digitalCollectionDao;
    private final EquityPropsDao equityPropsDao;
    private final SecondCollectionConfigDao secondCollectionConfigDao;
    private final StaticDataService staticDataService;
    private final UserVigorousCollectionRecordsService userVigorousCollectionRecordsService;
    private final UserPledgeCollectionRecordsService userPledgeCollectionRecordsService;


    @PostMapping(value = "/addPledgeTask", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加质押任务", notes = "添加质押任务", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    @Transactional(rollbackFor = Exception.class)
    public Result addPledgeTask(@Valid @RequestBody AddPledgeTaskRequest request) {
        //主表
        PledgeTaskInfo pledgeTaskInfo = BeanUtil.copyProperties(request, PledgeTaskInfo.class);
        //校验主表
        if(pledgeTaskInfo.getPledgeTaskName().length()>30){
            return Result.fail("任务名称不能超过30个字符");
        }

        if(pledgeTaskInfo.getLabel().length()>14){
            return Result.fail("标签不能超过14个字符");
        }

        String[] split = pledgeTaskInfo.getLabel().split(",");
        if(split.length>3){
            return Result.fail("标签不能超过3个");
        }

        if(pledgeTaskInfo.getPledgeTaskBeginTime().after(pledgeTaskInfo.getPledgeTaskEndTime())){
            return Result.fail("开始时间不能大于结束时间");
        }

        pledgeTaskInfo.insert();


        //激活NFT列表
        List<PledgeTaskVigorousCollection> pledgeTaskVigorousCollections = BeanUtil.copyToList(request.getVigorousCollectionList(), PledgeTaskVigorousCollection.class);
        if(pledgeTaskVigorousCollections.size() >9){
            return Result.fail("激活NFT不能超过9个");
        }

        for (PledgeTaskVigorousCollection pledgeTaskVigorousCollection : pledgeTaskVigorousCollections) {
            DigitalCollection digitalCollection = digitalCollectionDao.getById(pledgeTaskVigorousCollection.getCollectionId());
            Assert.notNull(digitalCollection,()->  new GlobalRunTimeException("激活NFT不存在"));

            pledgeTaskVigorousCollection.setPledgeTaskId(pledgeTaskInfo.getId());
            pledgeTaskVigorousCollection.setFirstTitle(digitalCollection.getFirstTitle());
            pledgeTaskVigorousCollection.setCollectionImage(digitalCollection.getCreationContent());
            pledgeTaskVigorousCollection.insert();
        }


        //质押NFT列表
        List<PledgeTaskCollection> pledgeTaskCollections = BeanUtil.copyToList(request.getPledgeTaskCollectionList(), PledgeTaskCollection.class);
        if(pledgeTaskCollections.size() >20){
            return Result.fail("质押NFT不能超过20个");
        }

        for (AddPledgeTaskCollectionRequest addPledgeTaskCollectionRequest : request.getPledgeTaskCollectionList()) {
            PledgeTaskCollection pledgeTaskCollection = BeanUtil.copyProperties(addPledgeTaskCollectionRequest, PledgeTaskCollection.class);
            DigitalCollection digitalCollection = digitalCollectionDao.getById(pledgeTaskCollection.getCollectionId());
            Assert.notNull(digitalCollection,()->  new GlobalRunTimeException("质押NFT不存在"));


            SecondCollectionConfig byCollectionIdAndMarketType = secondCollectionConfigDao.getByCollectionIdAndMarketType(digitalCollection.getId(), MarketTypeEnum.FREE_MARKET);
            Assert.notNull(byCollectionIdAndMarketType,()->  new GlobalRunTimeException("质押NFT不在自由市场"));

            pledgeTaskCollection.setCollectionImage(digitalCollection.getCreationContent());
            pledgeTaskCollection.setFirstTitle(digitalCollection.getFirstTitle());
            pledgeTaskCollection.setPledgeTaskId(pledgeTaskInfo.getId());
            pledgeTaskCollection.insert();

            //奖励列表
            List<PledgeTaskReward> pledgeTaskRewards = BeanUtil.copyToList(addPledgeTaskCollectionRequest.getPledgeTaskRewardList(), PledgeTaskReward.class);
            for (PledgeTaskReward pledgeTaskReward : pledgeTaskRewards) {

                if(pledgeTaskReward.getLinkType() == PledgeTaskRewardTypeEnum.EQUITY_PROP){
                    EquityProps equityProps = equityPropsDao.getById(pledgeTaskReward.getLinkId());
                    Assert.notNull(equityProps,()->  new GlobalRunTimeException("权益道具不存在"));

                    pledgeTaskReward.setLinkId(equityProps.getId());
                    pledgeTaskReward.setLinkName(equityProps.getFirstTitle());
                    pledgeTaskReward.setLinkImage(equityProps.getCreationContent());
                    pledgeTaskReward.setLinkCount(pledgeTaskReward.getLinkCount());
                }else if (pledgeTaskReward.getLinkType() == PledgeTaskRewardTypeEnum.POINTS){
                    pledgeTaskReward.setLinkId(0L);
                    pledgeTaskReward.setLinkName(PledgeTaskRewardTypeEnum.POINTS.getDescription());
                    pledgeTaskReward.setLinkImage("https://cdn.gometa.com.cn/scnft/default/integral.png");
                    pledgeTaskReward.setLinkCount(pledgeTaskReward.getLinkCount());
                }else if(pledgeTaskReward.getLinkType() == PledgeTaskRewardTypeEnum.NFT){
                    DigitalCollection collection = digitalCollectionDao.getById(pledgeTaskReward.getLinkId());
                    Assert.notNull(collection,()->  new GlobalRunTimeException("NFT不存在"));

                    pledgeTaskReward.setLinkName(collection.getFirstTitle());
                    pledgeTaskReward.setLinkImage(collection.getCreationContent());
                    pledgeTaskReward.setLinkId(collection.getId());
                    pledgeTaskReward.setLinkCount(pledgeTaskReward.getLinkCount());
                }

                pledgeTaskReward.setLinkCount(pledgeTaskReward.getLinkCount());
                pledgeTaskReward.setPledgeTaskId(pledgeTaskInfo.getId());
                pledgeTaskReward.setPledgeTaskCollectionId(pledgeTaskCollection.getId());
                pledgeTaskReward.insert();
            }
        }

        return Result.success();
    }

    @PostMapping(value = "/getPledgeTaskDetails", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "质押任务详情", notes = "添加质押任务", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<AdminPledgeTaskDetailsVO> getAdminPledgeTaskDetails(@Valid @RequestBody IdRequest request) {
        return Result.success(pledgeTaskInfoService.getAdminPledgeTaskDetails(request.getId()));
    }


    @PostMapping(value = "/pagePledgeTask", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "分页获取质押任务", notes = "分页获取质押任务", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AdminPagePledgeTaskVO> adminPagePledgeTask(@Valid @RequestBody PagePledgeTaskRequest request) {
        return PageResult.success(pledgeTaskInfoService.adminPagePledgeTask(request.getPledgeTaskName(),request.getPageNo(),request.getPageSize()));

    }

    @PostMapping(value = "/updatePledgeTaskIsEnable", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改是否启用", notes = "修改是否启用", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result updateIsEnable(@Valid @RequestBody UpdatePledgeTaskIsEnableRequest request) {
        pledgeTaskInfoService.adminUpdateIsEnable(request.getId(),request.getIsEnable());
        return PageResult.success();

    }

    @PostMapping(value = "/updatePledgeTaskIsSort", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改排序", notes = "修改排序", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result updatePledgeTaskIsSort(@Valid @RequestBody UpdatePledgeTaskIsSortRequest request) {
        pledgeTaskInfoService.adminUpdatePledgeTaskIsSort(request.getId(),request.getSort());
        return PageResult.success();
    }

    @PostMapping(value = "/updatePledgeTaskJoinCount", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改参与人数", notes = "修改参与人数", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result updatePledgeTaskJoinCount(@Valid @RequestBody UpdatePledgeTaskJoinCountRequest request) {
        pledgeTaskInfoService.updatePledgeTaskJoinCount(request.getId(),request.getJoinCount());
        return PageResult.success();
    }

    @PostMapping(value = "/updatePledgeTaskRuleUrl", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改规则图片", notes = "修改规则图片", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result updatePledgeTaskRuleUrl(@Valid @RequestBody UpdatePledgeTaskRuleUrlRequest request) {
        staticDataService.updateStaticData("pledge_task_rule_url",request.getPledgeTaskRuleUrl());
        return PageResult.success();
    }


    @PostMapping(value = "/pageVigorousRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "分页获取激活记录", notes = "分页获取激活记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AdminPageVigorousRecordVO> adminPageVigorousRecord(@Valid @RequestBody PageVigorousRecordRequest request) {
        return PageResult.success(userVigorousCollectionRecordsService.adminPageVigorousRecord(request.getPledgeTaskId(),request.getUserTel(),request.getPageNo(),request.getPageSize()));
    }

    @PostMapping(value = "/vigorousCollectionRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取激活关联的NFT", notes = "获取激活关联的NFT", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<List<AdmiVigorousCollectionVO>> adminVigorousCollectionRecord(@Valid @RequestBody IdRequest request) {
        return PageResult.success(userVigorousCollectionRecordsService.adminVigorousCollectionRecord(request.getId()));
    }


    @PostMapping(value = "/pagePledgeRecordsRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "分页获取挖宝记录", notes = "分页获取挖宝记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<AdminPagePledgeRecordsRecordVO> adminPagePledgeRecordsRecord(@Valid @RequestBody PageVigorousRecordRequest request) {
        return PageResult.success(userPledgeCollectionRecordsService.adminPagePledgeRecordsRecord(request.getPledgeTaskId(),request.getUserTel(),request.getPageNo(),request.getPageSize()));
    }


}
